package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.Product;
import com.aaa.vegetablemarketexpress.service.ProductService;
import com.aaa.vegetablemarketexpress.util.OssUtil;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @FileName: ProductController
 * @Description:
 * @Author: qxh
 * @CreateTime: 2025/9/5 20:16
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/product")
@Log4j2
public class ProductController {
/*    // 从配置文件注入头像存储路径和访问前缀
    @Value("${file.upload.avatar-path}")
    private String avatarSavePath;
    @Value("${file.access.prefix}")
    private String fileAccessPrefix;*/
    @Autowired
    private ProductService productService;

    @GetMapping("/selectProductById")
    public Result selectProductById(Long productId){
        return ResultUtil.success(productService.selectProductById(productId));
    }

    @PostMapping("/selectProductList")
    public Result selectProductList(@RequestBody Page<Product> page){
        return ResultUtil.success(productService.selectProductList(page));
    }

    @PostMapping("/insertProduct")
    public Result insertProduct(@RequestBody Product product){
        int result = productService.insertProduct(product);
        if (result > 0) {
            // 返回包含生成ID的完整商品对象
            return ResultUtil.success(product);
        } else {
            return ResultUtil.failed("商品添加失败");
        }
        //return ResultUtil.success(productService.insertProduct(product));
    }

    @PostMapping("/updateProduct")
    public Result updateProduct(@RequestBody Product product){
        return ResultUtil.success(productService.updateProduct(product));
    }

    @DeleteMapping("/deleteProductById")
    public Result deleteProductById(Long productId){
        return ResultUtil.success(productService.deleteProductById(productId));
    }
    /**
     *头像上传接口（本地存储）
     * @param file 前端上传的头像文件
     * @return 包含头像访问路径的Result
     *//*
    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.failed("上传文件为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png")) {
            return ResultUtil.failed("仅支持 jpg/png 格式");
        }

        if (file.getSize() > 2 * 1024 * 1024) {
            return ResultUtil.failed("文件不能超过 2MB");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;

        // 获取保存路径（来自配置）
        String fullPath = avatarSavePath; // 例如：uploads/avatar/

        try {
            Path path = Paths.get(fullPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            Path filePath = Paths.get(fullPath + fileName);
            *//*Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);*//*
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            }
            // 构造访问 URL
            String accessUrl = fileAccessPrefix + "avatar/" + fileName;

            Map<String, Object> result = new HashMap<>();
            result.put("url", accessUrl);
            result.put("fileName", fileName);

            log.info("头像上传成功，文件名：{}", fileName);

            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return ResultUtil.failed("上传失败：" + e.getMessage());
        }
    }*/

    /**
     * 上传商品图片
     * @param file 图片文件
     * @return 图片访问URL
     */
    /*@PostMapping("/uploadImage")
    public Result uploadProductImage(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = productService.uploadProductImage(file);

            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            data.put("url", imageUrl);
            result.put("url", imageUrl);
            result.put("data", data);

            log.info("商品图片上传成功");
            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("商品图片上传失败", e);
            return ResultUtil.failed("商品图片上传失败: " + e.getMessage());
        }
    }*/
    /**
     * 根据商品ID获取商品详情
     * @param productId 商品ID
     * @return
     */
    @GetMapping("/getProductDetail")
    @ResponseBody
    public Result getProductDetail(@RequestParam Long productId) {
        try {
            log.info("获取商品详情，商品ID: {}", productId);
            Product product = productService.selectProductById(productId);
            if (product != null) {
                return ResultUtil.success(product);
            } else {
                return ResultUtil.failed("商品不存在");
            }
        } catch (Exception e) {
            log.error("获取商品详情失败", e);
            return ResultUtil.failed("获取商品详情失败: " + e.getMessage());
        }
    }

    /**
     * 上传商品图片
     * @param file
     * @return
     */
    @PostMapping("/uploadProductImage")
    public Result uploadProductImage(@RequestParam("pic") MultipartFile file) {
        //调用工具类，进行上传
        return ResultUtil.success(OssUtil.uploadFile("product/images",file));
    }

}
